import 'package:app_settings/app_settings.dart';
import 'package:flutter/cupertino.dart';
import 'package:flutter/material.dart';
import 'package:camera/camera.dart';
import 'package:dio/dio.dart';
import 'package:permission_handler/permission_handler.dart';
import 'package:zhrs/mainpage/mainindex.dart';
import 'package:zhrs/utils/alert_utils.dart';
import 'dart:io';
import 'dart:convert';
import '../utils/http_utils.dart';
import '../model/base_model.dart';
import '../model/app_model.dart';
import '../model/user_model.dart';
import '../utils/path_utils.dart';
import '../api/api.dart';
import '../api/app_context.dart';
import '../pages/index.dart';
import 'dart:async';
import 'animation.dart';

class LoginFcPage extends StatefulWidget {
  LoginFcPage({Key key, this.title}) : super(key: key);
  final String title;

  @override
  _LoginFcPageState createState() => _LoginFcPageState();
}

class _LoginFcPageState extends State<LoginFcPage> {

  static CameraController  _controller;
  CameraDescription frontCamera;
  CameraDescription backCamera;

 AnimationController ancontroller;
  //获取相机
  List<CameraDescription> cameras;

  String _imageInfo;
  String _imagePath;
  String _authInfo;
  String _loginInfo;
  Timer  countDownTimer;
  bool runAni=true;
  static bool isinitialize =true;

  final GlobalKey<ScaffoldState> _scaffoldKey = GlobalKey<ScaffoldState>();
  Widget  Ratio=change();
  @override
  void initState() {

_change.login=this;
    super.initState();

    //计时器
   countDownTimer = new Timer.periodic(new Duration(seconds: 2), (timer){
     print(timer.tick);
      _onCapture();
    });
    //_imageInfo="图像信息";
    _loginInfo="登陆";
    cameras=BaseModel.of<AppModel>(context).cameras;


        for(CameraDescription cameraDescription in cameras){
          if(cameraDescription.lensDirection==CameraLensDirection.back){
            backCamera=cameraDescription;
          }
          if(cameraDescription.lensDirection==CameraLensDirection.front){
            frontCamera=cameraDescription;
          }
        }
        allowpermission();
  }

  allowpermission() async
  {
    PermissionGroup permissionGroup;
    if(Platform.isAndroid){
      permissionGroup=PermissionGroup.camera;
      }
    if(Platform.isIOS)
    {
      permissionGroup=PermissionGroup.photos;
    }
    Map<PermissionGroup, PermissionStatus> permissions = await   PermissionHandler()
        .requestPermissions([permissionGroup,PermissionGroup.microphone]);
    if(permissions[permissionGroup] == PermissionStatus.granted&&permissions[PermissionGroup.microphone] == PermissionStatus.granted){

      _controller=CameraController(frontCamera==null?backCamera:frontCamera, ResolutionPreset.low);
      _controller.initialize().then((_) {
        if (!mounted) {
          return;
        }
        setState(() {});
      });
    }
  }
  //拍照
  Future<void> _onCapture() async {
    /*   if(_loginInfo=="正在登陆...."){
      return null;
    }
    setState(() {
      _loginInfo="正在登陆....";
    });
  */
    print("进入了");
    String filePath;
    await PathUtils.instance.then((path) async {
      filePath = '${path.tempDirectory.path}/${timestamp()}.jpg';
      //filePath = '${path.documentsDirectory.path}/${timestamp()}.txt';
      // new File(filePath).writeAsStringSync("1123344");
      await _controller.takePicture(filePath);
      File file=File(filePath);
      file.readAsBytes().then((bytes){
        String base64str=base64Encode(bytes);
        print("bytes.length:${bytes.length}:${DateTime.now()}");
        //get accessToken
        getAuth().then((token){
          print("after getAuth:${DateTime.now()}");
          print("accessToken:$token");
          getFaceInfo(token,base64str).then((resp){
            print(resp);
            print("after getFace:${DateTime.now()}");
            Map face=resp.data;
            if(face['error_code']!=0){
              // setState(() {
              _imagePath=null;
              _imageInfo=null;
              //  });
              return;
            }
            int age=face['result']['face_list'][0]['age'];
            String gender=face['result']['face_list'][0]['gender']['type'];
            print('age:$age');
            print('gender:$gender');
            _login(gender, age);
            countDownTimer.cancel();

            _controller.dispose();
            print("登陆成功！！！！！！！！！！！！！！！！！！！！！！！！！！！！！");
            //Navigator.push(context, MaterialPageRoute(builder: (context){
            //  return IndexPage();
            // }));
          });
        }
        );
        //HttpUtils().post(path)
      });
    });
    return filePath;
  }
  _login(String gender,int age) async{
    UserModel userModel;
    if(gender=="male"&&age<60){
      userModel=UserModel(loginname: "111111",password: "111111",userId: "1");
    }else if(gender=="female"&&age<55){
      userModel=UserModel(loginname: "222222",password: "222222",userId: "2");
    }else{
      userModel=UserModel(loginname: "333333",password: "333333",userId: "3");
    }
   HttpManager.login(context, userModel,false);
    setState(() {
      _imageInfo='''${APP.userModel.username},$age岁，登陆成功！''';
      _loginInfo="登陆";
    });
    Future.delayed(Duration(milliseconds: 1500),(){
     Navigator.push(context,MaterialPageRoute(builder:(context) =>Mainindex( index: int.parse(userModel.userId))));
      //HttpManager.login(context, userModel,true);
    });
  }
  //切换镜头
  _onCameraRoll() async{
    CameraLensDirection _now=_controller.description.lensDirection;
    if (_controller != null) {
      await _controller.dispose();
    }
    if(_now==CameraLensDirection.back){
      _controller=CameraController(frontCamera, ResolutionPreset.low);
    }else{
      _controller=CameraController(backCamera, ResolutionPreset.low);
    }
    // If the controller is updated then update the UI.
    _controller.addListener(() {
      if (mounted) setState(() {});
      if (_controller.value.hasError) {
        print('Camera error ${_controller.value.errorDescription}');
      }
    });

    try {
      await _controller.initialize();
    } on CameraException catch (e) {
      print(e);
    }

    if (mounted) {
      setState(() {});
    }
  }




  @override
  Widget build(BuildContext context) {

    if(_controller==null||!_controller.value.isInitialized)
      {


      }
    else
      {
        setState(() {

        });

         Ratio=AspectRatio(
           aspectRatio: _controller.value.aspectRatio,
           child: CameraPreview(_controller),
         );

      }
    return Scaffold(
      key: _scaffoldKey,
      appBar: AppBar(title:Text("人脸识别登录"),centerTitle: true,
      ),
      body: Column(
        children: <Widget>[
          Container(
            height: 50,
          ),
          Center(
            child: Text("登录需要对您人脸识别",style: TextStyle(fontSize: 20),),
          ),
          Center(
            child: Text("请确认本人操作",style: TextStyle(fontSize: 15)),
          ),
          Container(
            padding: EdgeInsets.only(top: 50),
            child: new Align(
              alignment: Alignment.center,
              child: Container(
                decoration: BoxDecoration(border: Border.all(width:5, color: Colors.blue),
                    shape: BoxShape.rectangle,
                    borderRadius:
                    const BorderRadius.all(const Radius.circular(360.0))),
                child: new ClipRRect(
                  borderRadius: const BorderRadius.all(const Radius.circular(360.0)),
                  child:
                  Container(
                      width: 300.0,
                      height: 300.0,
                      child:
                      Stack(
                        children: <Widget>[
                          ListView (
                              physics: const NeverScrollableScrollPhysics(),
                              children: <Widget>[
                                Container(
                                  width: 300,
                                  child: Ratio,
                                ),
                              ]
                          ),
                          LogoApp(),
                        ],
                      )
                  ),
                ),
              ), //  LogoApp()
            ),
            // flex: 4,
          ),
          /*      Container(
            width: double.infinity,
            padding: EdgeInsets.only(left: 20.0,right: 20.0),
            child:  FlatButton(
              child: Text(
                _loginInfo,
                style: TextStyle(color: Colors.white),
              ),
              splashColor: Colors.white10,
              color: Theme.of(context).accentColor,
              onPressed: _onCapture,
            ),
          ),
*/
          Expanded(
            flex: 1,
            child: Container(
              margin: EdgeInsets.only(top: 30.0),
              child: Text(
                _imageInfo!=null?_imageInfo:'',
                style: TextStyle(color: Colors.red),
              ),
            ),
          ),
        ],
      ),
    );
  }

  @override
  void dispose() {
    countDownTimer.cancel();

    super.dispose();
   // _controller.dispose();
  }
  void showInSnackBar(String message) {
    _scaffoldKey.currentState.showSnackBar(SnackBar(content: Text(message)));
  }
  String timestamp() => DateTime.now().millisecondsSinceEpoch.toString();


  //获取access_token
  Future<String> getAuth() async{
    if(_authInfo!=null) return Future.value(_authInfo);
    String ak='ozt0wf9Un27lGz5XdSXzQpdk';
    String sk='oGMj53TgeI0t68hIAw5cOHq0CzgUPS1E';
    // 获取token地址
    String authHost = "https://aip.baidubce.com/oauth/2.0/token?";
    String getAccessTokenUrl = authHost
        // 1. grant_type为固定参数
        + "grant_type=client_credentials"
        // 2. 官网获取的 API Key
        + "&client_id=" + ak
        // 3. 官网获取的 Secret Key
        + "&client_secret=" + sk;

    BaseResp resp= await HttpUtils().post(getAccessTokenUrl);
    _authInfo=resp.data['access_token'];
    return resp.data['access_token'];
  }
  //人脸识别
  Future<BaseResp> getFaceInfo(String accessToken,String base64Str) async{
    String url='https://aip.baidubce.com/rest/2.0/face/v3/detect?access_token=$accessToken';
    Map data={'image':base64Str,'image_type':'BASE64','face_field':'age,gender'};
    Options options=Options();
    options.contentType=ContentType.json;
    return await HttpUtils().post(url,
        data: data,
        options: options
    );
  }

  getstate() async
  {

 // Timer timer = new Timer.periodic(new Duration(seconds: 1), (timer)async {
    // _controller.dispose();

  //});

  }
}

 class change extends StatefulWidget {
  @override
  State<StatefulWidget> createState() {
    // TODO: implement createState
    return _change();
  }
 }
 class _change extends State<change>
 {
   static  _LoginFcPageState login;

   static GlobalKey<_LoginFcPageState> key ;

   @override
  Widget build(BuildContext context) {



    // TODO: implement build
    return new Container(
      key: key,
      padding: EdgeInsets.fromLTRB(0,120,0,0),
      child: Center(
        child:Column(
          children: <Widget>[Container(
            alignment: Alignment.center,
            child: Text("未找到摄像机",style: TextStyle(fontSize: 20),) ,
          ),
            Row(
              children: <Widget>[
              Expanded(
                child: new Container(
                 alignment: Alignment.center,
                  child:  new FlatButton(
                  color: Colors.blue,
                  onPressed: () {

                 //  AppSettings.openAppSettings().then((va){
                   // Navigator.pop(context);
                    login.allowpermission();
                   //});
                  },
                   child: new Text('打开权限')),
                      )),],
                 )
               ],
              ),
        //  child: Text("未找到摄像机",style: TextStyle(fontSize: 20),),
      ),);
  }
 }